package com.qingzhu;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojovo.ResultVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/errorvo")
public class ErrorHandlerServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 将状态码强行设置为200正常响应
        resp.setStatus(HttpServletResponse.SC_OK);
        // 设置响应的数据格式
        resp.setContentType("application/json;charset=UTF-8");
        // 获取异常的状态码(500)
        Integer errorCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
        // 获取确切的错误消息(/ by zero)
        String errorMessage = (String) req.getAttribute("javax.servlet.error.message");
        // 获取异常产生的信息(java.lang.ArithmeticException: / by zero)
        Throwable errorThrowable = (Throwable) req.getAttribute("javax.servlet.error.exception");
        // 获取产生异常的服务名称
        String servletName = (String) req.getAttribute("javax.servlet.error.servlet_name");
        servletName = servletName == null ? "未知":servletName;
        System.out.println("检测到异常状态！"+errorCode+errorMessage);
        ResultVo resultVo = new ResultVo(errorCode,servletName+"服务器出现异常！异常原因："+errorThrowable);

        ObjectMapper mapper = new ObjectMapper();
        String errorString = mapper.writeValueAsString(resultVo);
        resp.getWriter().write(errorString);
    }
}
